from django.conf import settings
from django.http import JsonResponse
from django.views import View
from rest_framework.decorators import action
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from articles.models import Article, Channel, Comment
from questions.models import Label
from shicifang.apps.articles.serializers import ChannelsSerializer, ArticleListSerializer, \
    ArticleCreateSerializer, CommentSerializer, ArticleDetailSerializer, LabelsSerializer, ArticleSerializerForCreate


#卿凌 --3.1 频道列表
class ChannelsView(ModelViewSet):
    queryset = Channel.objects.all()

    serializer_class =  ChannelsSerializer



#获取发布文章中的标签列表
class LabelView(ModelViewSet):
    queryset = Label.objects.all()
    serializer_class = LabelsSerializer
    pagination_class = None



class ArticleView(ModelViewSet):

    queryset = Article.objects.all()
    serializer_class = ArticleListSerializer


#卿凌 --3.2  文章列表
    def list(self, request, *args, **kwargs):
        articles = super().get_queryset()
        serializer = ArticleListSerializer(instance=articles, many=True)
        return Response(serializer.data)


    @action(methods=["get"],detail = True)
    def  channel(self, request,pk):

        if pk == "-1":
            articles = self.get_queryset()
        else:
            channel = Channel.objects.get(id=pk)
            articles = self.get_queryset().filter(channel=channel)

        page = self.paginate_queryset(articles)
        if page is not None:
            serializer = ArticleListSerializer(page, many=True)
            return self.get_paginated_response(serializer.data)
        else:
            serializer = ArticleListSerializer(instance=articles, many=True)
            return Response(serializer.data)

    #卿凌 --3.3 收藏或取消
    @action(methods=["put"], detail=True)
    def collect(self, request,pk):
        try:
            user = request.user

        except Exception as e:
            user = None

        if user is not None and user.is_authenticated:
            article = self.get_object()
            collected_users = article.collected_users.all()
            if user in collected_users:
                article.collected_users.remove(user)
                article.save()
                return Response({"success": True, "message": "成功取消收藏"})

            else:
                article.collected_users.add(user)
                article.save()
                return Response({"success": True, "message": "成功收藏文章"})

        else:
            return Response({"success":False,"message":"请登陆后操作"})



#卿凌 --3.4 文章详情

    def retrieve(self, request, *args, **kwargs):

        article = super().get_object()
        article.visits +=1
        article.save()

        serializer = ArticleDetailSerializer(instance=article)

        return Response(serializer.data)

# 卿凌 --3.5 发表文章
#     def Create(self, request, *args, **kwargs):
#
#         try:
#             user = request.user
#         except:
#             user =  None
#         if user is not None and user.is_authenticated:
#
#             request.data["users"] = user.id
#             serializer = ArticleCreateSerializer(data=request.data)
#
#
#             serializer.is_valid(raise_exception=True)
#             article = serializer.save()
#             return Response({"success": True, "message": "成功发表","articleid": article.id})
#         else:
#             return Response({"success": False, "message": "请先登录"})
    def create(self, request, *args, **kwargs):

        try:
            user = request.user
        except Exception:
            user = None

        if user is not None and user.is_authenticated:
            request_params = request.data
            request_params['user'] = user.id
            serializer = ArticleSerializerForCreate(data=request_params)
            serializer.request = request
            serializer.is_valid(raise_exception=True)
            article = serializer.save()
            return Response({'success': True, 'message': '发表成功', 'articleid': article.id})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

# 卿凌 --3.6 评论文章
    @action(methods=["post"], detail=True)
    def publish_comment(self, request, id):
        try:
            user = request.user

        except Exception as e:
            user = None
        if user is not None and user.is_authenticated:

            article = self.get_object()
            article.comment_count += 1
            article.save()

            request.data['user'] = user.id
            request.data['article'] = article.id
            s = CommentSerializer(data=request.data)
            s.is_valid(raise_exception=True)
            s.save()
            return Response({'success': True, 'message': '评论成功'})
        else:
            return Response({'success': False, 'message': '未登录'}, status=400)

#卿凌  --3.7 搜索文章
class SearchViews(ModelViewSet):
    serializer_class = ArticleListSerializer

    #重写查询集
    def get_queryset(self):
        text = self.request.query_params.get("text")
        article = Article.objects.filter(title__contains=text)
        return article

